function OrderAdd_Code(id) {  
	var buffer = new StringBuffer();
	var hidden1="";
	var hidden2="hidden";
	if(id!=0)
	{
		var hidden1="hidden";
		var hidden2="";
	}
	buffer.append('<div id="orderid" class="crmsheet border-bottom" val="'+id+'"><div class="ctitle"><div class="cname">订单编号</div><div class="require">*</div></div><div class="ctext"><input id="txt_num" type="text" placeholder="" readonly="readonly" value=""/></div><div class="carrow"></div></div>');
	buffer.append('<div id="customernames" class="crmsheet border-bottom"><div class="ctitle"><div class="cname">客户名称</div><div class="require">*</div></div><div class="ctext"><input id="txt_customerid" customerid="0" type="text" placeholder="选择客户" readonly="readonly" value=""/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">付款方式</div><div class="require">*</div></div><div class="ctext"><select id="txt_paytype"><option value="0">现金支付</option><option value="1">支付宝</option><option value="2">微信支付</option><option value="3">财付通</option><option value="4">网银转账</option><option value="5">支票</option><option value="6">邮政汇款</option><option value="7">电汇</option><option value="8">其他</option></select></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">收货地址</div><div class="require">*</div></div><div class="ctext"><input id="txt_address" type="text" placeholder="填写收货地址" value=""/></div><div class="carrow"></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">联系人</div></div><div class="ctext"><select id="txt_contactid"><option value="">选择联系人</option></select></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom users" show="1"><div class="ctitle"><div class="cname">联合跟进人</div></div><div class="ctext"><input id="txt_followuser" touserid="" type="text" placeholder="选择联合跟进人" readonly="readonly" value=""/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom users" show="1"><div class="ctitle"><div class="cname">通知范围</div></div><div class="ctext"><input id="txt_sendrange" touserid="" type="text" placeholder="选择通知范围" readonly="readonly" value=""/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom" style="height:120px;"><div class="ctitle"><div class="cname">订单备注</div></div><textarea id="txt_bak" placeholder="填写订单备注" onfocus="ScrollTop()"></textarea></div>');
	buffer.append('<div id="product_tool" class="pline border-bottom"><font style="padding-left:10px;" class="'+hidden1+'">选择产品</font><table class="'+hidden2+'"><tr><td width="30%" >产品名称</td><td width="10%">单位</td><td width="15%">价格</td><td width="15%">数量</td><td width="15%">折扣</td><td width="15%">总金额</td></tr></table></div>');
	buffer.append('<div id="product_panel"><table id="porderdetail"></table></div>');
	buffer.append('<div id="add_product" class="add_product"><img src="img/add.png"/></div>');
	buffer.append('<div id="candelete" class="loading hidden" style="height:14px; margin-top:10px; margin-bottom:30px; float:left;">长按产品名称可以删除哦</div>');
	return buffer.toString();
};

var map;
var wsub;
var count=0;
var myScroll3;
function Init_OrderAdd(){
	var orderid=$("#orderid").attr("val");
	var customer;
	if(orderid!=0)
	{
		var data = {};
		data.act = "One_POrder";
		data.id=orderid;
		data.source=source;
		data.userid=userid;
		data.comid=comid;
		data.sign=GetSign(data.act);
		mui.getJSON(crm_domain, data, function (json) {
	            if (json.state) {
	                porder=json.data.porder;
	                $("#txt_num").val(porder.Num);
	                $("#txt_customerid").val(porder.CustomerName).attr("customerid",porder.CustomerID);
	                $("#txt_paytype").val(porder.PayType);
	                $("#txt_address").val(porder.Address);
	                $("#txt_contactid").val(porder.ContactID);
	                $("#txt_followuser").val(porder.FollowUser).parent().parent().attr("touserid",porder.FollowUserID);
	                $("#txt_sendrange").val(porder.SendRange).parent().parent().attr("touserid",porder.SendRangeID);
	                $("#txt_bak").val(porder.Bak);
	                Init_ContactByCustomerID(porder.CustomerID,porder.ContactID);
	                Init_OrderProduct(json.data.porderdetail);
	            } else {
					plus.nativeUI.toast(json.msg);
	            }
	    });
    }
	else{
		var data = {};
		data.act = "Table_Num";
		data.flag="order";
		data.comid=comid;
		data.sign=GetSign(data.act);
		mui.getJSON(crm_domain, data, function (json) {
	            if (json.state) {
	                $("#txt_num").val(json.data);
	            }
	    });
	}
	get("customernames").addEventListener("tap",function(){
		myScroll3 = OpenScroll2(4,"选择客户","",function(pageindex){
										Receive_CustomerSelect(pageindex);
								},function(){
									
								},CustomerSelect_Code(),70);
								//$("#contentlist2").append(Publish_Code());
								Receive_CustomerSelect(1);
								get("find2").addEventListener("tap",function(){
				      				$("#searchicon2").hide();
	      							$("#searchicons2").show();
	      							$("#keyword2").attr("placeholder","客户名称(支持拼音)，地址");
			    					if($("keyword2").val()!="")
			    					{
			    						//WorkMate_Search();
			    					}
				      			});
	});
	
	
	mui(".divmsg").on("tap",".users",function(){
			obj10=$(this);
			OpenWindow(4,"选择员工","确定",function(){
					var str1="",str2="",str3="",headimg="";
					touserid="";todepartid="";tocomid="";
	      			var count=0;
	      			mui.each(mui("#userlist input"),function(i,info){
	      				if(info.checked)
	      				{
	      					count++;
	      					touserid += info.value+",";
	      					str1 += info.getAttribute("val")+",";
	      					
	      				}
	      			});
	      			obj10.find("input").val(str1.TrimEnd(","));
	      			obj10.find("input").attr("touserid",touserid.TrimEnd(","));
					obj10.attr("touserid",touserid.TrimEnd(","));
	      			CloseWindow();
			});
			
			$("#contentlist4").html(CheckMate_Data());
			data = {};
			data.act = "DepartAndUser_Data";
			data.userid=userid;
			data.comid=comid;
			data.source=source;
			data.sign=GetSign(data.act);
			
			mui.getJSON(admin_domain, data, function(json) {
				Bind_CheckMate(json.data.user,json.data.depart);
				Init_CheckMate();
				
			});
			if($(this).attr("show")=="1")
	      	{
	      		$(".selectbar").hide();
	      	}else
	      	{
				$(".selectbar").show();  				
	      	}
	    });
	    
	    get("add_product").addEventListener("tap",function(){
	    	myScroll3 = OpenScroll2(4,"选择产品","",function(pageindex){
										Receive_ProductSelect(pageindex);
								},function(){
									
								},ProductSelect_Code("order"),70);
								Receive_ProductSelect(1);
								get("find2").addEventListener("tap",function(){
				      				$("#searchicon2").hide();
	      							$("#searchicons2").show();
	      							$("#keyword2").attr("placeholder","产品名称，编号");
			    					if($("keyword2").val()!="")
			    					{
			    						//WorkMate_Search();
			    					}
				      			});
	    });
	
};

function Init_OrderProduct(orderdetail){
	$.each(orderdetail,function(i,info){ 
		
		$("#product_panel table").append('<tr id="'+info.ProductID+'"><td width="30%" >'+info.ProductName+'</td><td width="10%">'+info.Unit+'</td><td width="15%">'+info.BuyPrice.toFixed(2)+'</td><td width="15%"><div style="width:40px; height:100%; margin:0 auto;" class="ui-border-radius"><input type="text" value="'+info.Count+'" onkeyup="Check_Money(this);Cal_POrder(this)" onfocus="ScrollTop()" /></div></td><td width="15%"><div style="width:40px; height:100%; margin:0 auto;" class="ui-border-radius"><input type="text" value="'+info.Percent+'" onkeyup="Check_Money(this);Cal_POrder(this)" onfocus="ScrollTop()"/></div></td><td width="15%">'+info.AllMoney.toFixed(2)+'</td></tr>');	
	});
};

function Init_ContactByCustomerID(customerid,contactid)
{
	data = {};
			data.act = "Find_Contact_ByCustomerID";
			data.userid=userid;
			data.comid=comid;
			data.source=source;
        	data.customerid = customerid;
        	data.sign=GetSign(data.act);
			
			mui.getJSON(crm_domain, data, function(json) {
				if (json.state) {
                var str = "<option value=''>选择联系人</option>";
                $.each(json.data.list, function (i, info) {
                    var selected = "";
                    if (info.ID == contactid) { selected = "selected='selected'"; }
                    str += "<option value='" + info.ID + "' "+selected+">" + info.Name + "</option>";
                });
                $("#txt_contactid").html(str);
                //LayerBox.Msg.Success(json.msg);
            	}
			});
};

function Save_Order() {
    var data = {};
        data.act = "Save_POrder";
        data.userid=userid;
		data.comid=comid;
        data.id = $("#orderid").attr("val");
        data.num = $("#txt_num").val();
        data.customerid = $("#txt_customerid").attr("customerid");
        data.customername = $("#txt_customerid").val();
        data.contactid = $("#txt_contactid").val();
        data.contactname = $("#txt_contactid").find("option:selected").text();
        data.followuser = $("#txt_followuser").attr("touserid");
        data.followusername = $("#txt_followuser").val();
        data.paytype = $("#txt_paytype").val();
        data.address = $("#txt_address").val();
        data.sendrange = $("#txt_sendrange").attr("touserid"); 
        data.senddate = $("#txt_followuser").val();
        data.bak = $("#txt_bak").val();
        data.source = source; 
        data.version = version;
        data.count = 0;
        data.allmoney = 0;
        var porderdetail = new Array();
        var error = false;
        if (data.customerid=="0") {
            plus.nativeUI.toast("请选择客户");
            return;
        }
        if (data.paytype.Trim()== "") {
            plus.nativeUI.toast("请选择付款方式"); 
            return;
        }
        if (data.address.Trim()=="") {
            plus.nativeUI.toast("请填写收货地址");
            return;
        }
        $("#porderdetail tr").each(function (i, row) {
            var detail = "";
                var input = $(row);
                detail += input.attr("id") + "_"; //拼接产品id
                input = $(row).find("td:eq(1)");
                detail += input.html() + "_"; //拼接计量单位
                input = $(row).find("td:eq(2)");
                var costprice = parseFloat(input.html());
                detail += input.html() + "_"; //拼接价格
                input = $(row).find("td:eq(3) input");
                if (input.val().Trim()==""  || input.val().Trim()=="0") {
                    plus.nativeUI.toast("请填写数量");
                    input.focus();
                    error = true;
                    return true;
                }
                var count = parseInt(input.val());
                detail += input.val() + "_"; //拼接数量
                input = $(row).find("td:eq(4) input");
                if (input.val().Trim()=="" || input.val().Trim()=="0") {
                    plus.nativeUI.toast("请填写折扣");
                    input.focus();
                    error = true;
                    return true;
                }
                var percent = parseFloat(input.val());
                detail += input.val() + "_"; //拼接折扣
                detail += (costprice * count * percent / 100).toFixed(2); //拼接总金额
                data.count += count;
                data.allmoney += costprice * count * percent / 100;
                porderdetail.push(detail);
            
        });
        if (error) {
            return false;
        }
        
        data.porderdetail = porderdetail + "";
        if(data.porderdetail=="")
        {
        	plus.nativeUI.toast("请选择产品");
        	return;
        }
        data.sign=GetSign(data.act);
		plus.nativeUI.showWaiting( "正在保存..." );
        
		mui.getJSON(crm_domain, data, function (json) {
			plus.nativeUI.closeWaiting();
			plus.nativeUI.toast(json.msg);
            if (json.state) {
                CloseWindow();
                if(data.id==0)
                {
                	Clear_Form();
                	Order_Search();
                	FindCrmReport();
                }else{
                	Init_OrderDetail();
                	obj.find(".orderprice").html("总额："+data.allmoney.toFixed(2));
                }
            } 
        });
};
